<?php
class UploadComponent extends Object
{
	var $path = 'post';

	function setPath($path) {
		$this->path = IMG_PATH . DS . $path;
		
		if(!file_exists($this->path)) {
			mkdir($this->path, 0777);
		}
		
		if (!is_writeable($this->path)) {
			debug("You must allow proper permissions for image processing. And the folder has to be writable.Run \"chmod 777 on '{$this->path}' folder\"");
			exit();
		}
	}
	
	function checkSize($size) {
		if ($size > 5000000) {
			return __('Limit size error 5MB', true);
		}
		return null;
	}
	
	
	/**
	 * Enter description here ...
	 * @param FileUpload $data
	 * @param Integer $id
	 * @param Filename $old
	 * @return string
	 */
	function upload($data, $id = null, $old = null) {
		
		//if( !is_dir($this->path) ) mkdir($this->path, 0755, true);
		$filetype = $this->getFileExtension($data['name']);
		$filetype = strtolower( $filetype );
		if(!empty($id)) {
			$filename = $id;
		} else {
			$filename = time();
		}
		
		$filename .= ".$filetype";
		
		if (is_uploaded_file( $data['tmp_name'] )) {
			$oldFile = $this->path . DS . (empty($old) ? $filename : $old);
			if(file_exists($oldFile)) {
				unlink($oldFile);
			}
			copy($data['tmp_name'], $this->path . DS . $filename);
			
		} else {
			return null;			
		}
		return $filename;
	}
	
	/*Copy tmp Image file */
	function process($fileData, $fileName) {
		$filetype = $this->getFileExtension( $fileName );
		$filetype = strtolower( $filetype );
		
		$_fname = md5(time().$fileName);
		$_fname .= ".$filetype";
		if (is_uploaded_file($fileData)) {
			copy($fileData, $this->path . DS . $_fname);
		}
		return $_fname;
	}
	
	/**
	 * Get File Extension ...
	 * @param Filename $str
	 * @return string
	 */
	function getFileExtension($str) {
		$i = strrpos($str, ".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str, $i+1, $l);
		return $ext;
	}

	/**
	 * Get Image Extension ...
	 * @param Image Header $imagetype
	 * @return boolean|string
	 */
	function getImageExtension($imagetype) {
		if(empty($imagetype)) return false;

		switch($imagetype) {
			case IMAGETYPE_GIF	: return 'gif';
			case IMAGETYPE_JPEG	: return 'jpg';
			case IMAGETYPE_PNG	: return 'png';
			case IMAGETYPE_SWF	: return 'swf';
			case IMAGETYPE_PSD	: return 'psd';
			case IMAGETYPE_BMP	: return 'bmp';
			case IMAGETYPE_TIFF_II : return 'tiff';
			case IMAGETYPE_TIFF_MM : return 'tiff';
			case IMAGETYPE_JPC	: return 'jpc';
			case IMAGETYPE_JP2	: return 'jp2';
			case IMAGETYPE_JPX	: return 'jpf';
			case IMAGETYPE_JB2	: return 'jb2';
			case IMAGETYPE_SWC	: return 'swc';
			case IMAGETYPE_IFF	: return 'aiff';
			case IMAGETYPE_WBMP	: return 'wbmp';
			case IMAGETYPE_XBM	: return 'xbm';
			default				: return false;
		}
	}
}
?>